<?php

namespace app\merchants\services;

use think\Exception;

/**
 * 微信交互
 */
class SysWechatService
{

    private $appid = 'wxe63e9fce6062ebf3';
    private $secrect = 'a5fef6d0f919df682e4562a560800a74';

    static $qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?";
    static $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
    static $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";

    /**
     * 获取二维码
     * @throws Exception
     */
    public function getQrcode()
    {
        $accessToken = $this->getToken($this->appid, $this->secrect);
        $url = $this->getQRCodeData($accessToken, time());


    }


    /**
     * 获取accessToken
     * @param $appid
     * @param $appsecret
     * @return mixed
     * 获取token
     * @throws Exception
     */
    protected function getToken($appid, $appsecret)
    {
        $url = self::$token_url."appid=" . $appid . "&secret=" . $appsecret;
        $token = request_get($url);
        $arr = json_decode(json_encode(json_decode(stripslashes($token))), true);
        if (!isset($arr['access_token'])){
            throw new Exception('获取二维码失败');
        }

        return $arr['access_token'];
    }


    /**
     * 获取关注二维码ticket
     * @param     $accessToken
     * @param     $fqid
     * @return string
     * @throws Exception
     */
    protected function getQRCodeData($accessToken, $fqid): string
    {
        $url = self::$qrcode_url . 'access_token=' . $accessToken;

        //生成临时二维码
        $qrcode = [
            'action_name' => "QR_SCENE",
            'action_info' => [
                'scene' => [
                    'scene_id' => $fqid
                ]]
        ];
        $data =  http_post_json($url, json_encode($qrcode,true));
        print_r($data);die;
        $urldata  = json_decode($data);

        if (!$urldata) {
            throw new Exception('获取二维码失败');
        }
        $ticket = urlencode($urldata['ticket']);
        return self::$qrcode_get_url . 'ticket=' . $ticket . '';

    }


}